package com.cq.base.retrofit.a

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.cq.base.R
import kotlinx.coroutines.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.logging.HttpLoggingInterceptor

/**
 * 作者: CQ
 * 日期: 2021-06-03
 * 说明:
 */
class RetrofitActivity : AppCompatActivity(), CoroutineScope by MainScope() {
    override fun onCreate(savedInstanceState : Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_retrofit)
        launch {
            Log.e("TAG1", "GlobalScope.launch...  Thread：${Thread.currentThread().name}")
            val data = withContext(Dispatchers.IO) {
                Log.e("TAG2", "GlobalScope.launch...  Thread：${Thread.currentThread().name}")
                Retrofit2.getInstance().getService<Api>().getBanner()
            }
            Log.e("TAG3", "GlobalScope.launch...  Thread：${Thread.currentThread().name}")
            Log.e("data", data.toString())
        }


        launch {
            val data1 = withContext(Dispatchers.IO) {
                val body : RequestBody = """{"billId":"8dc03385c4fa11ebac3a000c29b1f10"}""".toRequestBody("application/json;charset=UTF-8".toMediaTypeOrNull())
                Retrofit2.getInstance("http://110.90.126.133:32099/", mutableMapOf("pageNum" to "1", "pageSize" to "10")).getService<Api>().queryPageDetails(
                    "c3pqZ18xYzExYTI0MjI0MTQ0YmFiYjUyYTEwMWE3NWY3MzUxNV8xMjM0NTY3OA", body, body
                )
            }
            Log.e("data", data1)
        }
    }

    /**
     * 日志拦截器
     */
    private fun initLogInterceptor() : HttpLoggingInterceptor {
        val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message : String) {
                Log.i("Retrofit", message)
            }
        })
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        return interceptor
    }

    override fun onDestroy() {
        cancel()
        super.onDestroy()
    }

}